package cn.elead.chaos.ip;

import java.io.File;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;

import cn.elead.chaos.core.util.StringUtils;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * util class
 * 
 * @author chenxin<chenxin619315@gmail.com>
 */
@Slf4j
public class Util {

	public static final String IP_URL = "http://ip-api.com/json/%s?lang=zh-CN";

	/**
	 * write specfield bytes to a byte array start from offset
	 * 
	 * @param b
	 * @param offset
	 * @param v
	 * @param bytes
	 */
	public static void write(byte[] b, int offset, long v, int bytes) {
		for (int i = 0; i < bytes; i++) {
			b[offset++] = (byte) ((v >>> (8 * i)) & 0xFF);
		}
	}

	/**
	 * write a int to a byte array
	 * 
	 * @param b
	 * @param offet
	 * @param v
	 */
	public static void writeIntLong(byte[] b, int offset, long v) {
		b[offset++] = (byte) ((v >> 0) & 0xFF);
		b[offset++] = (byte) ((v >> 8) & 0xFF);
		b[offset++] = (byte) ((v >> 16) & 0xFF);
		b[offset] = (byte) ((v >> 24) & 0xFF);
	}

	/**
	 * get a int from a byte array start from the specifiled offset
	 * 
	 * @param b
	 * @param offset
	 */
	public static long getIntLong(byte[] b, int offset) {
		return (((b[offset++] & 0x000000FFL)) | ((b[offset++] << 8) & 0x0000FF00L) | ((b[offset++] << 16) & 0x00FF0000L) | ((b[offset] << 24) & 0xFF000000L));
	}

	/**
	 * get a int from a byte array start from the specifield offset
	 * 
	 * @param b
	 * @param offset
	 */
	public static int getInt3(byte[] b, int offset) {
		return ((b[offset++] & 0x000000FF) | (b[offset++] & 0x0000FF00) | (b[offset] & 0x00FF0000));
	}

	public static int getInt2(byte[] b, int offset) {
		return ((b[offset++] & 0x000000FF) | (b[offset] & 0x0000FF00));
	}

	public static int getInt1(byte[] b, int offset) {
		return ((b[offset] & 0x000000FF));
	}

	/**
	 * string ip to long ip
	 * 
	 * @param ip
	 * @return long
	 */
	public static long ip2long(String ip) {
		String[] p = ip.split("\\.");
		if (p.length != 4)
			return 0;

		int p1 = ((Integer.valueOf(p[0]) << 24) & 0xFF000000);
		int p2 = ((Integer.valueOf(p[1]) << 16) & 0x00FF0000);
		int p3 = ((Integer.valueOf(p[2]) << 8) & 0x0000FF00);
		int p4 = ((Integer.valueOf(p[3]) << 0) & 0x000000FF);

		return ((p1 | p2 | p3 | p4) & 0xFFFFFFFFL);
	}

	/**
	 * int to ip string
	 * 
	 * @param ip
	 * @return string
	 */
	public static String long2ip(long ip) {
		StringBuilder sb = new StringBuilder();

		sb.append((ip >> 24) & 0xFF).append('.').append((ip >> 16) & 0xFF).append('.').append((ip >> 8) & 0xFF).append('.').append((ip >> 0) & 0xFF);

		return sb.toString();
	}

	/**
	 * check the validate of the specifeld ip address
	 * 
	 * @param ip
	 * @return boolean
	 */
	public static boolean isIpAddress(String ip) {
		String[] p = ip.split("\\.");
		if (p.length != 4)
			return false;

		for (String pp : p) {
			if (pp.length() > 3)
				return false;
			int val = Integer.valueOf(pp);
			if (val > 255)
				return false;
		}

		return true;
	}

	/**
	 * 获取IP地址
	 * 
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		if (request == null) {
			return "unknown";
		}
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Forwarded-For");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Real-IP");
		}

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}

		return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
	}

	/**
	 * 是否内网IP
	 * 
	 * @param ip
	 * @return
	 */
	public static boolean internalIp(String ip) {
		byte[] addr = textToNumericFormatV4(ip);
		return internalIp(addr) || "127.0.0.1".equals(ip);
	}

	/**
	 * 将IPv4地址转换成字节
	 * 
	 * @param text IPv4地址
	 * @return byte 字节
	 */
	public static byte[] textToNumericFormatV4(String text) {
		if (text.length() == 0) {
			return null;
		}

		byte[] bytes = new byte[4];
		String[] elements = text.split("\\.", -1);
		try {
			long l;
			int i;
			switch (elements.length) {
			case 1:
				l = Long.parseLong(elements[0]);
				if ((l < 0L) || (l > 4294967295L))
					return null;
				bytes[0] = (byte) (int) (l >> 24 & 0xFF);
				bytes[1] = (byte) (int) ((l & 0xFFFFFF) >> 16 & 0xFF);
				bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
				bytes[3] = (byte) (int) (l & 0xFF);
				break;
			case 2:
				l = Integer.parseInt(elements[0]);
				if ((l < 0L) || (l > 255L))
					return null;
				bytes[0] = (byte) (int) (l & 0xFF);
				l = Integer.parseInt(elements[1]);
				if ((l < 0L) || (l > 16777215L))
					return null;
				bytes[1] = (byte) (int) (l >> 16 & 0xFF);
				bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
				bytes[3] = (byte) (int) (l & 0xFF);
				break;
			case 3:
				for (i = 0; i < 2; ++i) {
					l = Integer.parseInt(elements[i]);
					if ((l < 0L) || (l > 255L))
						return null;
					bytes[i] = (byte) (int) (l & 0xFF);
				}
				l = Integer.parseInt(elements[2]);
				if ((l < 0L) || (l > 65535L))
					return null;
				bytes[2] = (byte) (int) (l >> 8 & 0xFF);
				bytes[3] = (byte) (int) (l & 0xFF);
				break;
			case 4:
				for (i = 0; i < 4; ++i) {
					l = Integer.parseInt(elements[i]);
					if ((l < 0L) || (l > 255L))
						return null;
					bytes[i] = (byte) (int) (l & 0xFF);
				}
				break;
			default:
				return null;
			}
		} catch (NumberFormatException e) {
			return null;
		}
		return bytes;
	}

	/**
	 * 服务器IP
	 * 
	 * @return
	 */
	public static String getHostIp() {
		try {
			return InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e) {
		}
		return "127.0.0.1";
	}

	/**
	 * 服务器主机名
	 * 
	 * @return
	 */
	public static String getHostName() {
		try {
			return InetAddress.getLocalHost().getHostName();
		} catch (UnknownHostException e) {
		}
		return "未知";
	}

	public static String getCityInfo(String ip) {
		// db
		String dbPath = Util.class.getResource("/ip2region.db").getPath();
		File file = new File(dbPath);
		if (file.exists() == false) {
			log.error("Error: Invalid ip2region.db file");
			return null;
		}
		// 查询算法
		int algorithm = DbSearcher.BTREE_ALGORITHM; // B-tree
		// DbSearcher.BINARY_ALGORITHM //Binary
		// DbSearcher.MEMORY_ALGORITYM //Memory
		try {
			DbConfig config = new DbConfig();
			DbSearcher searcher = new DbSearcher(config, dbPath);
			// define the method
			Method method = null;
			switch (algorithm) {
			case DbSearcher.BTREE_ALGORITHM:
				method = searcher.getClass().getMethod("btreeSearch", String.class);
				break;
			case DbSearcher.BINARY_ALGORITHM:
				method = searcher.getClass().getMethod("binarySearch", String.class);
				break;
			case DbSearcher.MEMORY_ALGORITYM:
				method = searcher.getClass().getMethod("memorySearch", String.class);
				break;
			}
			DataBlock dataBlock = null;
			if (Util.isIpAddress(ip) == false) {
				log.error("Error: Invalid ip address");
				return null;
			}
			dataBlock = (DataBlock) method.invoke(searcher, ip);
			return dataBlock.getRegion();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * 远程获取IP信息
	 * 
	 * @param ip
	 * @return
	 */
	public static String getRemoteCityInfo(String ip) {
		String address = "内网IP";
		// 内网不查询
		if (Util.internalIp(ip)) {
			return address;
		}

		String rspStr = HttpUtil.get(String.format(IP_URL, ip));
		if (StringUtils.isEmpty(rspStr)) {
			log.error("获取地理位置异常 {}", ip);
			return address;
		}
		JSONObject obj = JSONUtil.parseObj(rspStr);
		String country = obj.getStr("country");
		String region = obj.getStr("regionName");
		String city = obj.getStr("city");
		address = country + "|" + region + "|" + city;
		return address;
	}

	private static boolean internalIp(byte[] addr) {
		if (ObjectUtil.isNull(addr) || addr.length < 2) {
			return true;
		}
		final byte b0 = addr[0];
		final byte b1 = addr[1];
		// 10.x.x.x/8
		final byte SECTION_1 = 0x0A;
		// 172.16.x.x/12
		final byte SECTION_2 = (byte) 0xAC;
		final byte SECTION_3 = (byte) 0x10;
		final byte SECTION_4 = (byte) 0x1F;
		// 192.168.x.x/16
		final byte SECTION_5 = (byte) 0xC0;
		final byte SECTION_6 = (byte) 0xA8;
		switch (b0) {
		case SECTION_1:
			return true;
		case SECTION_2:
			if (b1 >= SECTION_3 && b1 <= SECTION_4) {
				return true;
			}
		case SECTION_5:
			switch (b1) {
			case SECTION_6:
				return true;
			}
		default:
			return false;
		}
	}
}
